package com.chb.aspect;

import com.alibaba.fastjson.JSON;
import com.chb.annotation.LogAnnotation;
import com.chb.model.entity.Staff;
import com.chb.model.entity.SysOperLog;
import com.chb.service.SysOperLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author: 陈海彬
 * @date: Created in 2023/10/16 19:56
 * @description: 日志
 * @modified By:
 * @version: 1.0
 */

@Component
@Aspect
public class LogAspect {
    @Pointcut("@annotation(com.chb.annotation.LogAnnotation)")
    private void pointcut() {
    }

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysOperLogService sysOperLogService;
    @Autowired
    private HttpSession session;

    @Around("pointcut()")
    public Object my(ProceedingJoinPoint joinPoint) {
        //添加日志--日志对象。
        SysOperLog sysOperLog = new SysOperLog();
        sysOperLog.setOperTime(new Date());//操作时间

        Staff staff = (Staff) session.getAttribute("staff");
        sysOperLog.setOperName(staff.getStaffname()); //可以从session获取当前登录者信息
        sysOperLog.setRequestMethod(request.getMethod());//设置请求方式get post delete
        sysOperLog.setOperUrl(request.getRequestURI()); //设置请求的路径
        sysOperLog.setOperip(request.getRemoteAddr());//设置请求的ip地址
        //获取切面切入的方法对象.
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Object[] args = joinPoint.getArgs();
        sysOperLog.setOperParam(JSON.toJSONString(args));//设置操作参数

        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        sysOperLog.setBusinessType(annotation.business_type());//设置业务类型
        sysOperLog.setMethod(method.getName()); //设置方法名
        try {
            Object result = joinPoint.proceed();
            sysOperLog.setJsonResult(JSON.toJSONString(result));
            sysOperLog.setStatus(0);
            return result;
        } catch (Throwable e) {
            sysOperLog.setStatus(1);
            throw new RuntimeException("操作错误");
        } finally {
            //添加日志
            sysOperLogService.addLog(sysOperLog);
        }
    }
}
